#!/bin/sh

masterLists="common/master_lists"
previousTotalsFile="common/report/previousTotals"
errorLog="common/report/errors"
emailArchive="common/report/archive"


# extract previous result counts
previousErrorsCount=`sed '1q;d' $previousTotalsFile`
previousUnavailableCount=`sed '2q;d' $previousTotalsFile`
previousGeoblockCount=`sed '3q;d' $previousTotalsFile`
previousIgnoredCount=`sed '4q;d' $previousTotalsFile`
previousSuccessCount=`sed '5q;d' $previousTotalsFile`

# calculate overall total result counts from master files
totalErrorsCount=`cat $masterLists/errorList | grep [[:alnum:]] | wc -l`
totalUnavailableCount=`cat $masterLists/unavailableList | grep [[:alnum:]] | wc -l`
totalGeoblockCount=`cat $masterLists/geoblockList | grep [[:alnum:]] | wc -l`
totalIgnoredCount=`cat $masterLists/ignoredList | grep [[:alnum:]] | wc -l`
totalSuccessCount=`cat $masterLists/successList | grep [[:alnum:]] | wc -l`

# calculate the newly added results for each category since the previous count
newErrorsCount=`expr $totalErrorsCount - $previousErrorsCount`
newUnavailableCount=`expr $totalUnavailableCount - $previousUnavailableCount`
newGeoblockCount=`expr $totalGeoblockCount - $previousGeoblockCount`
newIgnoredCount=`expr $totalIgnoredCount - $previousIgnoredCount`
newSuccessCount=`expr $totalSuccessCount - $previousSuccessCount`

# calculate the sum of new results since the previous count
newResultsSum=`expr $newErrorsCount + $newUnavailableCount + $newGeoblockCount + $newIgnoredCount + $newSuccessCount`

# compile report from log reports
echo "Health Report:

-- New report --
Error:        $newErrorsCount/$newResultsSum
Unavailable:  $newUnavailableCount/$newResultsSum
Geo-block:    $newGeoblockCount/$newResultsSum
Ignored:      $newIgnoredCount/$newResultsSum
Success:      $newSuccessCount/$newResultsSum

-- Master doneList length: `cat $masterLists/doneList | grep [[:alnum:]] | wc -l`

-- Totals --
Error:        $totalErrorsCount
Unavailable:  $totalUnavailableCount
Geo-block:    $totalGeoblockCount
Ignored:      $totalIgnoredCount
Success:      $totalSuccessCount

-- Process tree --
`ps f -o args`

-- Errors --
`cat $errorLog`" > email_body

# send report as email
mutt -s "Health report `date +%d/%m/%y`" "mandy@firemail.cc" < email_body

# archive files and (if successful) prepare for next run

# archive report
cp email_body $emailArchive/`date +%d-%m-%y`.log &&
# archive previous totals file
cp $previousTotalsFile $emailArchive/`date +%d-%m-%y`.count &&
# reset error log
echo -n > $errorLog &&
# set previous totals file
echo -n "$totalErrorsCount
$totalUnavailableCount
$totalGeoblockCount
$totalIgnoredCount
$totalSuccessCount" > $previousTotalsFile
